import { useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { message, Button, Form, Input, Divider, Popover } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import { couponinfoCheck, couponinfoExport } from '@/services/activity';
import type { ProColumns } from '@ant-design/pro-table';

import styles from './style.less';
import { cloneDeep } from 'lodash';

export const TEXT_USE_RULE_TYPE_NAME = {
  0: { text: '0-无规则' },
  1: { text: '1-满XX元减XX元' },
  2: { text: '2-【产品/组合产品】支付减免权益（0元换取商品）' },
  3: { text: '3-整单满XX元，【产品/组合产品】支付减免权益（0元换取商品）' },
  4: { text: '4-【产品/组合产品】折扣（减免的费率）' },
  5: { text: '5-整单满XX元，获得【产品/组合产品】折扣（减免的费率）' },
  6: { text: '6-【产品/组合产品】支付权益（以固定价钱买商品）' },
  7: { text: '7-整单满XX元，获得【产品/组合产品】支付权益（以固定价钱买商品）' },
  8: { text: '8-指定产品满XX元获得XX元减免（0元换取商品）' },
  9: { text: '9-指定产品满XX元获得支付权益（以固定价钱买商品）' },
  10: { text: '10-指定产品满XX元获得【产品/组合产品】折扣（减免的费率）' },
  11: { text: '11-反复核销并记录扫码次数的券' },
  12: { text: '12-整单满XX元，整单减折扣' },
  13: { text: '13-整单满XX元，指定产品获得XX元减免' },
  14: { text: '14-白名单产品折扣减免' },
  15: { text: '15-升舱' },
  16: { text: '16-指定外送费' },
  17: { text: '17-白名单产品满XX元获得XX元减免' },
  100: { text: '100-非会员卡' },
  101: { text: '101-寄送商品' },
  201: { text: '201-免外送费' },
  203: { text: '203-优先取餐' },
};

const ENUM_RULE_DETAIL = {
  STOREB: '门店限制',
  STOREW: '门店限制',
  DATEB: '日期限制',
  DATEW: '日期限制',
  TIMEB: '时间限制',
  TIMEW: '时间限制',
  DWEEKB: '星期限制',
  DWEEKW: '星期限制',
  DMONTHB: '天数限制',
  DMONTHW: '天数限制',
  ONLYONEB: '必须任意消费',
  REUSABLECOUNTOFDAY: '使用次数限制',
  SPECIALB: '流动盘精选店不能使用',
  CATEB: '产品类别不适用ADV',
  CONDIMENTB: '优惠不适用于配料',
  REUSABLECOUNTOFTIME: '优惠适用于配料',
};

const ActivityList: React.FC = () => {
  const [modalFileForm] = Form.useForm();
  const [tableData, setTableData] = useState([]);

  const getTextForUseMarketing = (useMarketing: string) => {
    let str = '';
    const useMarketingBro = useMarketing.split(',') || [];
    useMarketingBro.forEach((item, index) => {
      str = str + ENUM_RULE_DETAIL[item] || item;
      if (index !== useMarketingBro.length - 1) {
        str = str + '，';
      }
    });
    return str;
  };

  const queryList = async (type: boolean) => {
    const activityIds = modalFileForm.getFieldValue('activityIds') || '';

    console.log('查询', activityIds);
    const { code, data } = await couponinfoCheck({
      // activityIds: activityIds.split(','),
      activityIds: activityIds,
      checkCrossBrand: type,
    });

    if (code === 200 && data && data.couponCheckInfos) {
      data.couponCheckInfos.forEach((item: any) => {
        item.useMarketing = item.useMarketing
          ? getTextForUseMarketing(cloneDeep(item.useMarketing))
          : '';
      });

      setTableData(data.couponCheckInfos);
      // modalFileForm.resetFields()
      if (type) {
        if (data.checkResult) {
          message.success(data.checkMessage);
        } else {
          message.error(data.checkMessage);
        }
      }
    } else {
      message.error(data?.checkMessage || '查询失败');
    }
  };

  const exportExcel = async () => {
    try {
      const activityIds = modalFileForm.getFieldValue('activityIds') || '';
      const resUpdate: any = await couponinfoExport({ activityIds: activityIds });
      const url = window.URL.createObjectURL(resUpdate.data);
      const link = document.createElement('a');
      link.style.display = 'none';
      const Disposition = resUpdate?.Disposition || '';
      if (!Disposition) {
        message.error('暂无数据');
        return;
      }
      link.download = decodeURIComponent(Disposition?.split(`filename*=utf-8''`)[1]) || '导出文件'; // 下载的文件名称
      link.href = url;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  const columnOne: ProColumns<API.ProfileListItem>[] = [
    // 表格
    {
      title: '券名',
      dataIndex: 'activity',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '是否已生成',
      dataIndex: 'status',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        0: { text: '未生成' },
        1: { text: '已生成' },
      },
    },
    {
      title: '有效期模式',
      dataIndex: 'validThruRule',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        1: { text: '1-固定效期' },
        2: { text: '2-发放后开始计算' },
        3: { text: '3-激活后开始计算' },
        4: { text: '4-激活后按月开始计算' },
        5: { text: '5-激活后开始计算且结束时间固定' },
      },
    },
    {
      title: '活动定义',
      dataIndex: 'activityId',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动组',
      dataIndex: 'activityGroup',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动开始时间',
      dataIndex: 'activityStartTime',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动结束时间',
      dataIndex: 'activityEndTime',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '激活后多少天/月有效',
      dataIndex: 'delayDays',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '有效天/月数',
      dataIndex: 'activationDays',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
  ];

  const columnsTwo = [
    {
      title: '结账或折扣',
      dataIndex: 'tenderType',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: 'Sales计算规则',
      dataIndex: 'salesType',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        0: { text: '0-无sales' },
        1: { text: '1-sales固定' },
        2: { text: '2-sales不固定' },
        3: { text: '3-动态sales' },
        4: { text: '4-内部结算' },
        5: { text: '5-无sales' },
      },
    },
    {
      title: '券净值',
      dataIndex: 'sales',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '商城净值',
      dataIndex: 'couponPrice',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '第三方支付的折扣',
      dataIndex: 'discountinSales',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '给顾客开票的金额',
      dataIndex: 'invoiceAmountA',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '给第三方开票的金额',
      dataIndex: 'invoiceAmountB',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
  ];

  const columnsThree = [
    {
      title: '发放方式',
      dataIndex: 'placeType',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '发放电子券数量',
      dataIndex: 'count',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '单人可领数量',
      dataIndex: 'personLimitCount',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '发放渠道',
      dataIndex: 'placeChannelId',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '查询渠道',
      dataIndex: 'queryChannelId',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '使用渠道',
      dataIndex: 'useChannelId',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '是否异步发放',
      dataIndex: 'needGenAsynFile',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return <span> {record.needGenAsynFile === 0 ? '否' : '是'} </span>;
      },
      // valueEnum: {
      //   1: { text: '是' },
      //   0: { text: '否' },
      // },
    },
    {
      title: '是否通知第三方',
      dataIndex: 'isCallOuterApi',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return <span> {record.isCallOuterApi ? '是' : '否'} </span>;
      },
    },
  ];

  const columnsFour = [
    {
      title: '每张可使用次数',
      dataIndex: 'reusableCount',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '使用规则类型',
      dataIndex: 'useRuleType',
      ellipsis: true,
      width: 200,
      align: 'center',
      hideInSearch: true,
      valueEnum: TEXT_USE_RULE_TYPE_NAME,
    },
    {
      title: '产品规则ID',
      dataIndex: 'productIdRule',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '价格规则',
      dataIndex: 'priceRule',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '优惠价格',
      dataIndex: 'salePrice',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '优惠折扣',
      dataIndex: 'saleDiscount',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '产品ID',
      dataIndex: 'productId',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '产品描述',
      dataIndex: 'productDesc',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '券核销限制',
      dataIndex: 'isExcluded',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        0: { text: '0-不限制订单' },
        1: { text: '1-不做特殊处理' },
        2: { text: '2-限制订单只能核销这张券' },
      },
    },
    {
      title: '限制使用',
      dataIndex: 'storeIdLimit',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return <span> {record.storeIdLimit ? '是' : '否'} </span>;
      },
    },
    {
      title: '限制使用规则明细',
      dataIndex: 'useMarketing',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
      // render: (_, record) => {
      //   return (
      //     <Popover
      //       content={
      //         record.useMarketing ? getTextForUseMarketing(cloneDeep(record.useMarketing)) : ''
      //       }
      //       title={null}
      //     >
      //       <span>
      //         {record.useMarketing ? getTextForUseMarketing(cloneDeep(record.useMarketing)) : ''}
      //       </span>
      //     </Popover>
      //   );
      // },
    },
    {
      title: '是否动态券码',
      dataIndex: 'isDynamicCoupon',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        1: { text: '是' },
        0: { text: '否' },
      },
    },
    {
      title: '宅急送优惠CODE',
      dataIndex: 'onlineCode',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '是否跨品牌发放',
      dataIndex: 'crossBrandPlace',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        0: { text: '0-否' },
        1: { text: '1-是' },
        2: { text: '2-多品牌卡包发券' },
      },
    },
    {
      title: '多品牌卡包活动号',
      dataIndex: 'crossActivity',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
  ];

  return (
    <PageContainer>
      <div className={styles['form-bodys']}>
        <div className={styles['filter-body']}>
          <div>
            <Form
              form={modalFileForm}
              initialValues={{
                activityIds: '',
              }}
            >
              <Form.Item style={{ width: 600 }} label="券定义" name="activityIds">
                <Input placeholder="activityIds" />
                {/* <Input.TextArea rows={1} /> */}
              </Form.Item>
            </Form>
          </div>
          <div>
            <Button
              style={{ marginRight: 10 }}
              type="primary"
              key="query1"
              onClick={() => {
                queryList(false);
              }}
            >
              查询
            </Button>
            <Button
              style={{ marginRight: 10 }}
              type="primary"
              key="query2"
              onClick={() => {
                queryList(true);
              }}
            >
              跨品牌发券校验
            </Button>
            {tableData && tableData.length > 0 && (
              <Button
                type="primary"
                key="out"
                onClick={() => {
                  exportExcel();
                }}
              >
                导出
              </Button>
            )}
          </div>
        </div>
        <Divider orientation="left">基本信息</Divider>
        <ProTable<API.ProfileListItem>
          rowKey="id"
          dataSource={tableData}
          // @ts-ignore
          columns={columnOne}
          options={false}
          search={false}
          scroll={{ x: 800 }}
          pagination={false}
        />
        <Divider orientation="left">财务信息</Divider>
        <ProTable<API.ProfileListItem>
          rowKey="id"
          dataSource={tableData}
          // @ts-ignore
          columns={columnsTwo}
          options={false}
          search={false}
          scroll={{ x: 800 }}
          pagination={false}
        />
        <Divider orientation="left">发放信息</Divider>
        <ProTable<API.ProfileListItem>
          rowKey="id"
          dataSource={tableData}
          // @ts-ignore
          columns={columnsThree}
          options={false}
          search={false}
          scroll={{ x: 800 }}
          pagination={false}
        />
        <Divider orientation="left">核销信息</Divider>
        <ProTable<API.ProfileListItem>
          rowKey="id"
          dataSource={tableData}
          // @ts-ignore
          columns={columnsFour}
          options={false}
          search={false}
          scroll={{ x: 600 }}
          pagination={false}
        />
      </div>
    </PageContainer>
  );
};

export default ActivityList;
